package com.mission.schedule.CommonDialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.mission.schedule.R;
import com.mission.schedule.activity.MyStateActivity;
import com.mission.schedule.activity.NoteTypepxActivity;
import com.mission.schedule.annotation.ViewResId;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.TagCommandBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.entity.ScheduleTable;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日程标签对话框
 * Created by liwei on 2017/4/18.
 */

public class CalenderFlagDialog extends Dialog {
    private ListView state_lv;

    CallBack callBack;


    SharedPrefUtil sharedPrefUtil = null;
    Context context;
    WindowManager windowManager;

    private int lastIndex;

    ChooseStateAdapter adapter = null;
    List<TagCommandBean> list = new ArrayList<TagCommandBean>();
    private Map<Integer, Boolean> isSelected;

    App app = App.getDBcApplication();


    public CalenderFlagDialog(@NonNull final Context context,
                              @StyleRes int themeResId, WindowManager windowManager,
                              final String ids, String statename, final String repid) {
        super(context, themeResId);
        this.context = context;
        this.windowManager = windowManager;


        setCanceledOnTouchOutside(true);

        View view = LayoutInflater.from(context).inflate(R.layout.dialog_flag, null);
        setContentView(view);

        state_lv = view.findViewById(R.id.state_lv);
        View footview = LayoutInflater.from(context).inflate(R.layout.emptry_foolterview_white, null);
        state_lv.addFooterView(footview);

        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        list = app.QueryTagData(10);

        TagCommandBean map = new TagCommandBean();
        map.setCtgText("未分类");
        map.setCtgId("0");
        list.add(0, map);
        if (isSelected != null)
            isSelected = null;
        isSelected = new HashMap<Integer, Boolean>();
        for (int i = 0; i < list.size(); i++) {
            isSelected.put(i, false);
            if (repid.equals("") || repid == null) {
                if (list.get(i).getCtgText().equals(statename)) {
                    list.get(i).setCheck(true);
                    lastIndex = i;
                }
            } else {
                if (list.get(i).getCtgId().equals(statename)) {
                    list.get(i).setCheck(true);
                    lastIndex = i;
                }
            }
        }
        adapter = new ChooseStateAdapter(context, list, lastIndex);
        state_lv.setAdapter(adapter);
        state_lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        adapter.notifyDataSetChanged();
        state_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // 当前点击的CB
                boolean cu = !isSelected.get(position);
                // 先将所有的置为FALSE
                for (Integer p : isSelected.keySet()) {
                    isSelected.put(p, false);
                }
                // 再将当前选择CB的实际状态
                isSelected.put(position, cu);
                adapter.notifyDataSetChanged();
                String str = ((TagCommandBean) state_lv.getAdapter().getItem(position)).getCtgText();
                String coclor = ((TagCommandBean) state_lv.getAdapter().getItem(position)).getCtgDesc();
                if (coclor == null || coclor.isEmpty()){
                    coclor = "0";
                }
                if (repid.equals("") || repid == null) {
                    if (!ids.equals("重复")) {
                        updateColorStateSch(ScheduleTable.schColorType, coclor, ids);
                    }
                } else {
                    App.getDBcApplication().updateRepeatColorTypeState(repid, coclor);
                    Map<String, String> mapre = app.getSchReaId(repid, true);
                    if (mapre != null) {
                        if (DateUtil.parseDateTime(mapre.get("schDate") + " " + mapre.get("schTime"))
                                .after(DateUtil.parseDateTime(DateUtil.formatDateTime(new Date())))) {
                            updateColorStateSch(ScheduleTable.schColorType, coclor, mapre.get("schID"));
                        }
                    }
                }
                callBack.reminderEditTime(str, coclor);
                dismiss();
            }
        });
        view.findViewById(R.id.fenleiguanli).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, NoteTypepxActivity.class);
                intent.putExtra("type",0);
                context.startActivity(intent);
                dismiss();
            }
        });

    }

    private void updateColorStateSch(String key, String colortype, String id) {
        try {
            Map<String, String> upMap = new HashMap<String, String>();
            upMap.put(key, colortype);
            app.updateSchFocusState(upMap, "where schID=" + id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        WindowManager.LayoutParams params = window.getAttributes();
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        params.width = windowManager.getDefaultDisplay().getWidth();
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);

    }

    public interface CallBack {
        void reminderEditTime(String name, String id);
    }

    public CallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }

    public class ChooseStateAdapter extends BaseAdapter {
        private Context context;
        private List<TagCommandBean> mList;
        private int lastIndex;

        public ChooseStateAdapter(Context context, List<TagCommandBean> mList, int lastIndex) {
            this.context = context;
            this.mList = mList;
            this.lastIndex = lastIndex;
        }

        @Override
        public int getCount() {
            return mList == null ? 0 : mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            View view = convertView;
            ChooseStateAdapter.ViewWapper viewWapper = null;
            if (view == null) {
                view = LayoutInflater.from(context).inflate(
                        R.layout.adapter_choosestate, null);
                viewWapper = new ChooseStateAdapter.ViewWapper(view);
                view.setTag(viewWapper);
            } else {
                viewWapper = (ChooseStateAdapter.ViewWapper) view.getTag();
            }

            TextView state_item_title = viewWapper.getForDayTvTime();
            CheckBox state_item_cb = viewWapper.getForDayCb();

            state_item_title.setText(mList.get(position).getCtgText());
            state_item_cb.setChecked(mList.get(position).isCheck());


            return view;
        }

        class ViewWapper {
            private View view;
            private TextView state_item_title;
            private CheckBox state_item_cb;


            private ViewWapper(View view) {
                this.view = view;
            }

            private TextView getForDayTvTime() {
                if (state_item_title == null) {
                    state_item_title = (TextView) view
                            .findViewById(R.id.state_item_title);
                }
                return state_item_title;
            }

            private CheckBox getForDayCb() {
                if (state_item_cb == null) {
                    state_item_cb = (CheckBox) view
                            .findViewById(R.id.state_item_cb);
                }
                return state_item_cb;
            }
        }
    }
}
